package com.xiao.community.payweb;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.xiao.community.entity.GoodsEntity;
import com.xiao.community.entity.OrderEntity;
import com.xiao.community.feign.BarginFeign;
import com.xiao.community.service.GoodsService;
import com.xiao.community.service.OrderService;
import com.xiao.community.service.PintuanOrderService;
import com.xiao.group.common.Vo.BarginHuodongEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("community/web")
public class PayWebController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private PintuanOrderService pintuanOrderService;
    @Autowired
    private OrderService orderService;

    @Autowired
    BarginFeign barginFeign;

    private final String APP_ID = "2021000118614937";
    private final String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDn7ZQ3fzmiKg4JiV30vq5emy6OIBgy5iYGRIi96AbR39J/YMnhHD8rpns7yKlvLfwzkzKDlRxmPx8Cdv+3fJo4R3b4HVSuBghcW3r/jzFyvCVIXy+tfo1O3+O9Qz+qj+kaF1VQ5cX5UcPDWa7boPinhfhPTa2lohlW24NFbUvjg4KqdUCu3xGxVckMY7SjyYaE/0gwNqKqmNFOwIH5dvr5LbiWqqgC8bBFZUgoRT/KxYKfbltP2DmZFrrIMikaDZ8xHYTHqUoIX9L4qXmSG500NvCo7CG6kjujo0viRNvGnn38cbMuuMJiISs7CGcxxx+RyRZ95z16rO57jB+bT6NhAgMBAAECggEAV9s9vFAriuyXa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ZdpM1tKCz4EdoVPL823m0NUqicnZqoMVh6/ylZf0+2uzIcDimD+mAtcg2lZwzagGTHIUFzW0ev7Evx2bBHXBLBcsO98THCjnAFBze/dU4wO6Tooj8dWlqFcMRkWCuu8FEZ9UyVg3vqQ";
    private final String CHARSET = "UTF-8";
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjB9ZqU0Q2gvMJBxyzGb5Y45h0ZCVNbAlRy6tTxmfFHZ3qvXMCo2jJeJP7VgBjgHMkrhNVHWDV+3rRgSw8kyyuw8MO/KDSPU6T0z/hMfadrtvf9ALe5HcbO9W4d5sJucmEdMh7IPtfKCEQ0JOX/uN64vFp5U+CJR0hFWDyw9mhlGgGmgaKVRjO+4J3z88GZX6ICXIfC5ryE7rDPbIei0NaEMUMQlog8vk9gNwyDX1S/383NeoAbuDdHo4GUIstMBpkhOuVm+szCjD6TujSg+RoW1JD7Aq4KDejNcNvIKsKZcRh2B1C0DCIGyGg0L6wJKCM4hvaLSR9NyiFqWmKRUwBQIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";

    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "";
    //http://localhost:88/api/collage/return/notifyUrl

    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:88/api/community/web/returnUrl";




    @RequestMapping("takepart")
    public void alipay(HttpServletResponse httpResponse,
                       @RequestParam("goodsid")Integer goodsid,
                       @RequestParam("uuid")String uuid,
                       @RequestParam("pintuanid")Integer pintuanid,
                       @RequestParam("userid")Integer userid) throws IOException {
        GoodsEntity goodsEntity = goodsService.findbygoodsid(goodsid);
        SecureRandom r= new SecureRandom();
        Integer orderId = pintuanOrderService.canyupintuan(uuid, pintuanid, userid);
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();
        //付款金额，必填
        String total_amount =Double.toString(goodsEntity.getGoodsPrice());
        //订单名称，必填
        String subject =goodsEntity.getGoodsName();
        //商品描述，可空
        String body = goodsEntity.getGoodsInfomation();
        request.setBizContent("{\"out_trade_no\":\""+ orderId +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }


    //普通购买
    @RequestMapping("gotomai")
    public void gotomai(HttpServletResponse httpResponse,
                         @RequestParam("goodsid")Integer goodsid,
                         @RequestParam("userid")Integer userid,
                        @RequestParam("orderid")Integer orderid) throws IOException {
        GoodsEntity goodsEntity = goodsService.findbygoodsid(goodsid);
        SecureRandom r= new SecureRandom();
        if(orderid==0){
            orderid = goodsService.goumai(userid, goodsid);
        }
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();
        //付款金额，必填
        String total_amount =Double.toString(goodsEntity.getGoodsPrice());
        //订单名称，必填
        String subject =goodsEntity.getGoodsName();
        //商品描述，可空
        String body = goodsEntity.getGoodsInfomation();
        request.setBizContent("{\"out_trade_no\":\""+ orderid.toString() +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }
    //砍价购买
    @RequestMapping("gotokan")
    public void gotokan(HttpServletResponse httpResponse,
                         @RequestParam("barginId")Integer barginId,
                         @RequestParam("userid")Integer userid) throws IOException {
        BarginHuodongEntity barginHuodongEntity = barginFeign.info(barginId, userid);


        SecureRandom r= new SecureRandom();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();
        //付款金额，必填
        String total_amount =Double.toString(barginHuodongEntity.getGoodsPrice());
        //订单名称，必填
        String subject =barginHuodongEntity.getGoodsName();
        //商品描述，可空
        String body = barginHuodongEntity.getInforma();
        request.setBizContent("{\"out_trade_no\":\""+ barginHuodongEntity.getBarginId().toString() +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }



    //开团
    @RequestMapping("kaituan")
    public void kaituan(HttpServletResponse httpResponse,
                        @RequestParam("pintuanid")Integer pintuanid,
                        @RequestParam("userid")Integer userid,
                        @RequestParam("goodsid")Integer goodsid) throws IOException {
        GoodsEntity goodsEntity = goodsService.findbygoodsid(goodsid);
        SecureRandom r= new SecureRandom();
        Integer orderid = goodsService.goumai(userid, goodsid);


        Integer orderId = pintuanOrderService.kaituan(userid, pintuanid);
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();
        //付款金额，必填
        String total_amount =Double.toString(goodsEntity.getGoodsPrice());
        //订单名称，必填
        String subject =goodsEntity.getGoodsName();
        //商品描述，可空
        String body = goodsEntity.getGoodsInfomation();
        request.setBizContent("{\"out_trade_no\":\""+ orderid.toString() +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();

    }

    //支付成功后
    @RequestMapping(value = "/returnUrl", method = RequestMethod.GET)
    public String returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);
          //  System.out.println("订单ID="+out_trade_no);

            OrderEntity orderEntity = orderService.findorderid(out_trade_no);
            orderEntity.setOrderStatus(1);
            boolean b = orderService.updateById(orderEntity);
            if(b){
                return "redirect:http://hgt.vaiwan.com/api/community/tolist/tolists";
            }else{
                return "http://hgt.vaiwan.com/api/community/tolist/tolists";
            }
            //支付成功，修复支付状态
//            payService.updateById(Integer.valueOf(out_trade_no))
        }else{
            return "no";//跳转付款失败页面
        }

    }

}
